package com.itheima.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class MultiHttpSecurityConfig {//多个无需再继承
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //在内存中配置
    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("seeumt").password("$2a$10$fCIwtIjVLxsRYMMnsZyXKuKOrfjIdfLThRanTB9DoNcPF/8QmnVYK").roles("admin")
                .and()
                .withUser("祥").password("$2a$10$zVayBbMkjdlwH4VGKxNwYufJLvtevA9l.qMfbr63m.wFrFfTS6g9y").roles("admin")
                .and()
                .withUser("test").password("$2a$10$yTEVKQmvfL9X5soQEq8qGeS1J7OzU6akRxbdZBuySCt8btEdgukyG").roles("user");
    }

    @Configuration
    @Order(1)
    public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
        }
    }

    @Configuration
    public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginProcessingUrl("/doLogin")
                    .permitAll()
                    .and()
                    .csrf().disable();
        }
    }

//    public static void main(String[] args) {
//        mima();
//    }
//
//    private static void mima() {
//        for (int i = 0; i < 10; i++) {
//            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//            System.out.println(encoder.encode("123"));
//        }
//    }
}
